package star.cloud.asme.base.fowable.listener.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.JavaDelegate;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.variable.api.persistence.entity.VariableInstance;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Component;
import star.cloud.asme.system.user.UserService;

import java.util.Map;

@Component("doBeforeEndEvent")
@RequiredArgsConstructor
@Slf4j
public class DoBeforeEndEvent implements JavaDelegate {

    private final MailSender mailSender;
    private final RuntimeService runtimeService;
    private final UserService userService;

    @Override
    public void execute(DelegateExecution execution) {
        log.info("doBeforeEndEvent is running");
        String initiator = (String) execution.getVariable("initiator");
        String email = userService.getEmailByUsername(initiator);
        Map<String, VariableInstance> variableInstances = runtimeService.getVariableInstances(execution.getId());
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(execution.getProcessInstanceId()).singleResult();
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("195288591@qq.com");
        message.setTo(email);
        message.setSubject(processInstance.getName() + "执行完成了。");
        String text = processInstance.getName() + "执行完成了。" + "\n流程实例编号为：" + execution.getId();
        message.setText(text);
        mailSender.send(message);
        variableInstances.forEach((variableName, variableInstance) -> runtimeService.removeVariable(execution.getId(), variableName));
        log.info("doBeforeEndEvent is finished");
    }


}
